package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.UserDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Description: No Description
 * User: Eric
 */
@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 通过用户名查询用户信息 包含角色与权限
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    /**
     * 编辑用户信息
     * @param user
     * @param roleIds
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(User user, Integer[] roleIds) {
        //根据id更新用户信息
        userDao.update(user);
        //根据id删除关联表信息
        userDao.deleteUserRole(user.getId());
        //添加关联表信息
        if (null != roleIds) {
            for (Integer roleId : roleIds) {
                userDao.addUserRole(roleId,user.getId());
            }
        }
    }

    /**
     * 新增用户信息
     * @param user
     * @param roleIds
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(User user, Integer[] roleIds) {
        userDao.add(user);
        if (null != roleIds) {
            for (Integer roleId : roleIds) {
                userDao.addUserRole(roleId,user.getId());
            }
        }
    }

    /**
     * 分页查询用户信息
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult<User> findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        if (null != queryPageBean.getQueryString()) {
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        Page<User> page =  userDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult<User>(page.getTotal(),page.getResult());
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @Override
    public User findById(int id) {
        return userDao.findById(id);
    }

    /**
     * 根据id查询用户角色信息
     * @param id
     * @return
     */
    @Override
    public List<Integer> findRoleIdsByUserId(int id) {
        return userDao.findRoleIdsByUserId(id);
    }

    /**
     * 根据id删除用户
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(int id) {
        userDao.deleteUserRole(id);
        userDao.deleteById(id);
    }
}
